#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

"""One-line documentation for flood module.

A detailed description of flood.
"""

__author__ = 'arb@google.com (Anthony Baxter)'

RIVER = 'javascript:PopupRiver'
RIVERLABELS = ['Station No','River Height (m)','Time of Observation','Flood Class','Tendency','Minor (m)','Moderate (m)','Major (m)']
RIVERELEMENTS = ['name', 'station','lat', 'long','height',
                 'floodClass','tendency', 'time','minorHeight','moderateHeight','majorHeight']

from BeautifulSoup import BeautifulSoup as BS
import simplejson
import urllib
import datetime


# HERE BE DRAGONS
# TODO(jmcgill): Replace with Fusion Tables when we have time to play with OAuth
# and verify that upload/drop is reliable.
def makeStyle(document, image, id):
  text = """<Style id="%s">
    <IconStyle>
      <Icon>
        <href>%s</href>
      </Icon>
    </IconStyle>
  </Style>
  """ % (id, image)
  document.append(text)

def floodLevelToStyle(level):
  # jmcgill, best coder, or bestEST coder?
  mapping = {
    'road': 'road',
  }

  return '#' + mapping[level]

def makePoint(document, point):
  style = floodLevelToStyle(point['floodClass'])
  text = """<Placemark>
    <styleUrl>%s</styleUrl>
    <name>%s</name>
    <description>Road expected to be closed Wednesday: %s</description>
    <Point>
      <coordinates>%s,%s</coordinates>
    </Point>
  </Placemark>""" % (style, point['name'], point['name'], point['long'], point['lat'])
  document.append(text)

def makeKml(data):
  # Why bother with the DOM when you can concat strings?
  document = []
  document.append("""<?xml version="1.0" encoding="utf-8"?>
  <kml xmlns="http://earth.google.com/kml/2.0">
  <Document><name>Brisbane Proposed Road Closures</name>""")

  # Create icon styles.
  base = "http://mapvisage.appspot.com/static/floodmap/images/rivers/"
  makeStyle(document, base + "closure_smaller2.png", "road")

  # Add points - TODO(jmcgill) Infowindows?
  for point in data:
    makePoint(document, point)

  document.append("</Document></kml>")
  return "".join(document)

def updateMap():
  from google.appengine.api import memcache
  # TODO(arb): also store in datastore
  memcache.set('qld', loadMaps())

def showMap():
  from google.appengine.api import memcache
  return memcache.get('qld')

def main():
  o = []
  for line in open('roads.csv'):
    line = line.strip()
    place, long,lat = line.split(',')
    o.append({'name':"%s" %(place), 'lat':lat, 'long':long,
              'floodClass': 'road'})
  print makeKml(o)


def main2():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
